package com.cdgeekcamp.redas.recr_page_worker.component;

import com.cdgeekcamp.redas.db.model.Nature;
import com.cdgeekcamp.redas.db.model.NatureRepository;
import com.cdgeekcamp.redas.db.model.R_CompanyNature;
import com.cdgeekcamp.redas.db.model.R_CompanyNatureRepository;
import com.cdgeekcamp.redas.lib.core.RecrPage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Optional;

@Component
public class NatureBuildServiceImpl implements RecrPageBuildService {
    @Autowired
    private NatureRepository natures;

    @Autowired
    private R_CompanyNatureRepository r_companyNatures;

    public Integer build(RecrPage recrPage, Integer... relatedIds) {
        ArrayList<String> companyNature = recrPage.getCompanyNature();

        for (String item : companyNature) {
            Optional<Nature> natureOpt = natures.findByName(item);
            Nature nature;

            if (natureOpt.isEmpty()) {
                nature = natures.save(new Nature(item));
                log.info(String.format("行业编号：%s不存在，新建中......", nature.getId()));
            } else {
                nature = natureOpt.get();
                log.info(String.format("行业编号：%s已经存在", nature.getId()));
            }

            Integer companyId = relatedIds[0];
            Integer natureId = nature.getId();

            Optional<R_CompanyNature> r_companyNature = r_companyNatures.findByCompanyIdAndNatureId(companyId, natureId);

            if (r_companyNature.isEmpty()) {
                r_companyNatures.save(new R_CompanyNature(companyId, natureId));
                log.info(String.format("公司：%s->行业：%s 关联不存在，新建中......", companyId, natureId));
            } else
                log.info(String.format("公司：%s->行业：%s 关联已经存在......", companyId, natureId));
        }

        return 0;
    }
}
